<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\visitor\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;

/**
 * 访客管理
 * Class User
 * @package app\worker\controller
 */
class Visitor extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'VisitorList';
    protected $view_table = 'view_new_app_meeting_info';




    /**
     * 来访客人
     * @auth         true
     * @menu true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-06T16:16:34+0800
     * @LastTime     2020-11-06T16:16:34+0800
     * @return       [type]                       [description]
     */
    public function index(){
                $this->title = '访客管理';
        $dbconf = $this->getconfig('vister_db');
        $uinfo = $this->getGuserinfo();

        $where = '';
        /**用户角色权限**/
        switch ($uinfo['db1']['authorize']) {
            case 1:
                $company_id = $this->request->param('company_id');
                if($company_id){
                    $where = 'companyid = '.$company_id;
                }
                $this->_query(Db::connect($dbconf)->table('view_user'))->where($where)
                                                            // ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                            ->like('name,company_name,mobile')
                                                            // ->equal('arrive_status')
                                                            // ->where('deleteTime is null')
                                                            // ->order('app_visittime desc')
                                                            
                                                            ->page();
                // $search[6] = 'companyid = '.$uinfo['db2']['companyid'];
                # code...
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                $status = $this->request->param('status');
                //$search[0] = $status=='1'?'appointment_status = 0':($status=='2'?'appointment_status in (1,3)':'');
                $search[0] = 'appointment_status !=0';
                $search[1] = 'companyid = '.$uinfo['db2']['companyid'];
                $create_at_first = trim($this->request->param('create_at_first'))?:'';
                $create_at_last = trim($this->request->param('create_at_last'))?:'';
                if($create_at_first!='' && $create_at_last!=''){
                    $search[2] = 'app_visittime between '.strtotime($create_at_first).' and '.strtotime($create_at_last);
                }else{
                    $search[2] = '';
                }
                # code...
                foreach ($search as $key => $value) {
                    # code...
                    if($value){
                        $where=$where.$value.' and ';
                    }
                }
                $where=substr($where,0,strlen($where)-5);

                $this->_query(Db::connect($dbconf)->table('view_new_app_meeting_info_copy'))->where($where)
                                                            ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                              // ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                            ->like('vister_name,app_company_name,app_address,vister_mobile')
                                                            ->equal('arrive_status')
                                                            ->where('deleteTime is null')
                                                            ->order('app_visittime desc')
                                                            ->group('vister_uid,address')
                                                            ->page();
                # code...
                break;
            case 8:
                $status = $this->request->param('status');
                $search[0] = $status=='1'?'appointment_status = 0':($status=='2'?'appointment_status in (1,3)':'');

                $company_res =  Db::connect($dbconf)->table('view_company')->field('id')->where(['property_id' => $uinfo['db2']['companyid']])->order('createtime desc')->select();

                if($company_res){
                    $inid = array_column($company_res, 'id');
                    $inid = implode(",", $inid);
                    $search[1] = 'companyid in ('.$inid.')';
                }else{
                    $search[1] = 'companyid = 0';
                }
                $company_id = $this->request->param('company_id');
                if($company_id){
                    $search[1] = 'companyid = '.$company_id;
                }
                
                # code...
                foreach ($search as $key => $value) {
                    # code...
                    if($value){
                        $where=$where.$value.' and ';
                    }
                }
                $where=substr($where,0,strlen($where)-5);

                $this->_query(Db::connect($dbconf)->table('view_new_app_meeting_info'))->where($where)
                                                            // ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                            ->like('vister_name,app_company_name,app_address')
                                                            ->equal('arrive_status')
                                                            // ->where('deleteTime is null')
                                                            ->group('app_company_id,vister_uid')
                                                            ->order('app_visittime desc')
                                                            ->page();


                break;
            default:
                # code...
                $this->error('无操作权限');
                break;
        }
        return 1;
        $this->_query(Db::connect($dbconf)->table('view_new_app_meeting_info_copy'))->where($where)
                                                            ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                            ->like('vister_name,app_company_name,app_address')
                                                            ->equal('arrive_status')
                                                            ->where('deleteTime is null')
                                                            ->order('app_visittime desc')
                                                            ->page();

    }

    /**
     * 访客管理(数据列表)
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index_bck()
    {
        $dbconf = $this->getconfig('vister_db');
        $uinfo = $this->getGuserinfo();

        $where = '';



       // array(9) { ["offset"]=> string(1) "1" ["length"]=> string(3) "160" ["spm"]=> string(10) "m-70-71-72" ["nickname"]=> string(4) "name" ["department"]=> string(3) "dep" ["companyname"]=> string(3) "com" ["status"]=> string(1) "1" ["create_at_first"]=> string(10) "2020-08-06" ["create_at_last"]=> string(10) "2020-08-20" }

        $nickname = trim($this->request->param('nickname'))?:'';
        $search[0] = $nickname!=''?'vister_name like "%'.$nickname.'%"':'';

        $department = trim($this->request->param('department'))?:'';
        $search[1] = $department!=''?'app_dept_name like "%'.$department.'%"':'';

        $companyname = trim($this->request->param('companyname'))?:'';
        $search[2] = $companyname!=''?'app_company_name like "%'.$companyname.'%"':'';

        $status = trim($this->request->param('status'))?:'';
        $search[3] = $status=='1'?'appointment_status = 0':($status=='2'?'appointment_status = 1':'');

        $create_at_first = trim($this->request->param('create_at_first'))?:'';
        $create_at_last = trim($this->request->param('create_at_last'))?:'';
        if($create_at_first!='' && $create_at_last!=''){
            $search[4] = 'app_visittime between '.strtotime($create_at_first).' and '.strtotime($create_at_last);
        }else{
            $search[4] = '';
        }
        $search[5] = 'app_visittime is not null and vister_uid is not null';



        /**用户角色权限**/
        switch ($uinfo['db1']['authorize']) {
            case 1:
                // $search[6] = 'companyid = '.$uinfo['db2']['companyid'];
                # code...
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                $search[6] = 'companyid = '.$uinfo['db2']['companyid'];
                # code...
                break;
            case 8:
                $company_res =  Db::connect($dbconf)->table('view_company')->field('id')->where(['property_id' => $uinfo['db2']['companyid']])->order('createtime desc')->select();

                if($company_res){
                    $inid = array_column($company_res, 'id');
                    $inid = implode(",", $inid);
                    $search[6] = 'companyid in ('.$inid.')';
                }else{
                    $search[6] = 'companyid = 0';
                }
                
                # code...
                break;
            default:
                # code...
                $this->error('无操作权限');
                break;
        }
        if($this->request->param('company_id')){
            $search[6] = 'companyid = '.$this->request->param('company_id');
        }

        foreach ($search as $key => $value) {
            # code...
            if($value){
                $where=$where.$value.' and ';
            }
        }
        $where=substr($where,0,strlen($where)-5);

        $offset = trim($this->request->param('offset'))?:0;
        $length = trim($this->request->param('length'))?:10;

		$this->title = '访客管理';

        $res = Db::connect($dbconf)->table('view_new_app_meeting_info')->where($where)->order('app_visittime desc')->group('vister_uid')->limit($offset, $length)->select();
        $res = Db::connect($dbconf)->table('view_new_app_meeting_info')->where($where)->order('app_visittime desc')->paginate($length);
        $page = $res->render();
        $count = Db::connect($dbconf)->table('view_new_app_meeting_info')->where($where)->count();

        $pagehtml = $this->pagenew($res, $page = true,$count, $limit = 0,$offset,$length);


        return $this->fetch('index',[
            'list'=>$res,
            'pagehtml'=>$pagehtml
        ]);

    }

    /**
     * 添加访客
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {

          $dbconf = $this->getconfig('vister_db');
		  $res2= Db::connect($dbconf)->table('view_new_app_meeting_info');
		  //var_dump($res);
		  if($this->request->param('vister_name')){
		  $vister_name= trim($this->request->param('vister_name'));
		  $app_company_name=$this->request->param('app_company_name');
		  $app_dept_name=$this->request->param('app_dept_name');
		  $app_user_name=$this->request->param('app_user_name');
		  $data=[
		      //'name'=> $name,
		      'vister_name'=>$vister_name,
		      'app_company_name'=>$app_company_name,
		      'app_dept_name'=>$app_dept_name,
		      'app_user_name'=>$app_user_name
		      ];
		      //$data_name=['name'=>$name];
		      //var_dump($data);
		  
		    $res = Db::connect($dbconf)->table($this->view_table)->insert($data);
		  //  $res1= Db::connect($dbconf)->table($this->user)->insert($data_name);
		    $this->success('添加名单成功','');
		  }
			$this->_form($res2, 'form');
        $this->_form($this->table, 'form');
    }


    /**
     * 修改访客
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {

        //var_dump($this->request->param());

        $this->_form($this->table, 'form');
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }
    }

    /**
     * 更改访客状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
        // var_dump($this->request->param(''));
        // exit();
        $arrive_id = $this->request->param('arrive_id');
        $app_id = $this->request->param('app_id');
        $meeting_id = $this->request->param('meeting_id');
        $status = $this->request->param('status');

        $dbconf = $this->getconfig('vister_db');
        // if($status == '0'){
            /*无需未到访*/
            $data = [
                'status' => $status,
                'auditing' => 1, 
            ];
            $where = 'id = '.$app_id;
            /**app表状态**/
            $res = Db::connect($dbconf)->table('appointment')->where($where)->data($data)->update();
            /**arrive表状态**/
            $data = [
                'arrivetime' => time(),
                'passtime' => time(), 
                'meettime' =>time(),
                'deptleavetime' =>time()+10,
                'status' => 4,  
            ];
            $where = 'id = '.$arrive_id;
            $res = Db::connect($dbconf)->table('arrive')->where($where)->data($data)->update();
            /**meeting表状态**/
            // $data = [
            //     'arrivetime' => time(),
            //     'passtime' => time(), 
            //     'meettime' =>time(),
            //     'deptleavetime' =>time()+10,
            //     'status' => 4,
            // ];
            // $where = 'id = '.$meeting_id;
            // $res = Db::connect($dbconf)->table('meeting')->where($where)->data($data)->update();

        $tips = $status?'已到访':'未到访';
        $this->success('成功设为'.$tips);
        // return $this
        // }else{
        //     /*已到访*/
        //     $data = ['status' => $status];
        //     $where = 'id = '.$app_id;
        //     $res = Db::connect($dbconf)
        //         ->table('appointment')
        //         ->where($where)
        //         ->data($data)
        //         ->update();            
        // }


        // $this->_save($this->table, ['status' => input('status', '0')]);
    }

    /**
     * 删除访客
     * @auth true
     * @param   $[name] [<description>]
     *          vister_uid 访客uid
     *          companyid  公司id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {

        //批量删除code waiting......
        // $this->_delete($this->table);
		// if($this->request->isPost()){      
		// $id=trim($this->request->param('id'));
        $vister_uid = $this->request->param('vister_uid');
        $companyid = $this->request->param('companyid')?:'NULL';
		// dump($id);
        $where = 'uid = '.$vister_uid.' and companyid = '.$companyid;
		// $data=Db::name('VisitorList')->where($where)->delete();
        $data1 = [
            'is_deleted' =>1
        ];
        $data2 = [
            'deletetime' => time()
        ]; 

        $res1 = Db::name('VisitorList')
                ->where($where)
                ->data($data1)
                ->delete();
        $dbconf = $this->getconfig('vister_db');

        $res2 = Db::connect($dbconf)
                ->table('visiterlist')
                ->where($where)
                ->data($data2)
                ->delete();
        
		// if($data){
	   $this->success('数据删除成功！');
		// }
		// }
    }
    /**
     * 访客访问详情记录
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-06T14:20:39+0800
     * @LastTime     2020-11-06T14:20:39+0800
     * @return       [type]                       [description]
     */
    public function details(){
        $dbconf = $this->getconfig('vister_db');
        $uinfo = $this->getGuserinfo();
        $vis_uid = $this->request->param('userid');
        $vis_uinfo = Db::connect($dbconf)->table('view_user')->where('id = '.$vis_uid)->find();
        $this->assign('vis_uinfo',$vis_uinfo);
        //var_dump($this->request->param(''));
        switch ($uinfo['db1']['authorize']) {
            case 1:
                // roleid  5 6 物业 和 普通公司的门卫 目前以普通的
                $where = 'vister_uid = '.$vis_uid;
                // $res = Db::connect($dbconf)->table()->where()->select();
                $this->_query(Db::connect($dbconf)->table('view_new_app_meeting_info_copy'))->where($where)
                                                            // ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                            ->like('vister_name,app_company_name,app_address')
                                                            ->equal('arrive_status')
                                                            // ->where('deleteTime is null')
                                                            ->order('app_visittime desc')
                                                            ->page();
                # code...
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                // roleid  5 6 物业 和 普通公司的门卫 目前以普通的
                $where = 'vister_uid = '.$vis_uid.' and companyid = '.$uinfo['db2']['companyid'];
                // $res = Db::connect($dbconf)->table()->where()->select();
                $this->_query(Db::connect($dbconf)->table('view_new_app_meeting_info_copy'))->where($where)
                                                            // ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                            ->like('vister_name,app_company_name,app_address')
                                                            ->equal('arrive_status')
                                                            // ->where('deleteTime is null')
                                                            ->order('app_visittime desc')
                                                            ->page();
                # code...
                break;
            case 8:
                $companyid = $this->request->param('vis_companyid');
                // roleid  5 6 物业 和 普通公司的门卫 目前以普通的
                $where = 'vister_uid = '.$vis_uid.' and companyid = '.$companyid;
                // $res = Db::connect($dbconf)->table()->where()->select();
                $this->_query(Db::connect($dbconf)->table('view_new_app_meeting_info_copy'))->where($where)
                                                            // ->where('appointment_uid is not null and vister_uid is not null and vister_arrivetime is not null')
                                                            ->like('vister_name,app_company_name,app_address')
                                                            ->equal('arrive_status')
                                                            // ->where('deleteTime is null')
                                                            ->order('app_visittime desc')
                                                            ->page();
                # code...
                break;
            default:
                $this->error("无权限操作");
                # code...
                break;
        }



    }

}
